<template>
    <div class="song-audio">
        <audio id="player" 
            :src="url" 
            ref="player"
            controls = "controls" 
            preload = "true"
            @canplay="startPlay"
            @ended="ended"
        ></audio>
    </div>
</template>

<script>
import {mapGetters} from 'vuex';
export default {
    name: 'song-audio',
    computed: {
        ...mapGetters([
            'id',  // 音乐id
            'url',  // 音乐链接
            'isPlay'    // 播放状态
        ])
    },
    watch:{
        //监听播放还是暂停
        isPlay: function(){
            this.togglePlay();
        }
    },
    methods:{
        //开始、暂停
        togglePlay() {
            let player = this.$refs.player;
            if(this.isPlay){
                player.play();
            }else{
                player.pause();
            }
        },
        //获取链接后准备播放
        startPlay(){
            let player = this.$refs.player;
            //开始播放
            player.play();
            // setTimeout("player.play()",1000 );  //延迟一秒
            this.$store.commit('setIsPlay', true);
        },
        //播放完成之后触发
        ended(){
        //    this.isPlay = false
        this.$store.commit('setIsPlay', false);
        },
        
    }
}
</script>

<style>
    .song-audio {
        /* display: inline; */
        display: none;
    }
</style>